﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.IO;
namespace TA.Turbo.Controls
{
	/// <summary>
	/// Uploads a file as part of a form submission.
	/// </summary>
	public class FileUpload : BaseComplexValueControl<UploadedFile>
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public FileUpload()
		{
			this.Tag = HtmlTextWriterTag.Span;
		}
		#endregion
		#region PROPS
		/// <summary>
		/// Gets true if this control is able to receive focus on the client, otherwise false.
		/// </summary>
		public override bool CanReceiveFocus
		{
			get
			{
				return true;
			}
		}
		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		static readonly Random _rnd = new Random();
		#endregion
		#region PROPS
		/// <summary>
		/// Used internally by the control to transfer the file to the server.
		/// </summary>
		protected internal override string SerializedValue
		{
			get
			{
				return "";
			}
			set
			{
				UploadedFile file = null;
				if (!string.IsNullOrEmpty(value))
				{
					string token = value;
					FileUploadOperation oper = FileUploadOperation.Get(HttpContext.Current, token);
					if (oper != null)
					{
						file = oper.Files[0];
						FileUploadOperation.Remove(HttpContext.Current, oper);
					}
				}
				this.Value = file;
			}
		}
		#endregion
		#region METHODS
		#region INIT
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.Page.Load += new EventHandler(Page_Load);
		}
		/// <summary>
		/// Registers includes.
		/// </summary>
		protected internal override void RegisterIncludes(IncludeCollection includes)
		{
			base.RegisterIncludes(includes);

			includes.Add(Script.Json);
			includes.Add(Script.Element_ClearChildNodes);
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.FileUpload.FileUpload.js", typeof(FileUpload)));
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.FileUpload.FileUploadContext.js", typeof(FileUpload)));
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.FileUpload.FileUploadProgress.js", typeof(FileUpload)));
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.FileUpload.Turbo_FileUpload.js", typeof(FileUpload)));
		}
		/// <summary>
		/// Loads the value for this control.
		/// </summary>
		/// <param name="nvc"></param>
		protected override void LoadStateValue(System.Collections.Specialized.NameValueCollection nvc)
		{
			base.LoadStateValue(nvc);

			foreach (UploadedFile file in HttpContext.Current.get_Files())
			{
				if (string.Equals(file.ControlUniqueID, this.UniqueID))
				{
					this.Value = file;
					break;
				}
			}
		}

		void Page_Load(object sender, EventArgs e)
		{
			if (this.TPage.JavaScript != true)
			{
				this.Page.Form.Enctype = "multipart/form-data";
			}
		}
		#endregion
		#region RENDER
		/// <summary>
		/// Adds "AppRootUrl" attribute whose value is application's root URL.
		/// </summary>
		/// <param name="writer"></param>
		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			base.AddAttributesToRender(writer);

			writer.AddAttribute("AppRootUrl", this.ResolveUrl("~/"));
		}
		public override void RenderLoadScriptInternal(HtmlTextWriter writer, string varName)
		{
		}
		/// <summary>
		/// Renders either 1) INPUT tag of type FILE if JavaScript is not confirmed enabled or 2) IFRAME which displays a small sub-page with the INPUT tag of type FILE if JavaScript is confirmed enabled.
		/// </summary>
		/// <param name="writer"></param>
		protected override void RenderContents(HtmlTextWriter writer)
		{
			if (this.TPage != null && this.TPage.JavaScript == true)
			{
				string token = _rnd.Next(0, int.MaxValue).ToString();
				string iframeUrl =
					this.ResolveUrl(
						string.Format("~/TurboFileUpload.axd?i={0}&t={1}", this.ClientID, token));

				writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "220px");
				writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "26px");
				writer.AddAttribute("frameborder", "0");
				writer.AddAttribute("scrolling", "no");
				writer.AddAttribute("allowtransparency", "yes");
				writer.AddAttribute(HtmlTextWriterAttribute.Src, iframeUrl);
				writer.RenderBeginTag(HtmlTextWriterTag.Iframe);
				writer.Write(" ");
				writer.RenderEndTag();
			}
			else
			{
				writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
				writer.AddAttribute(HtmlTextWriterAttribute.Type, "file");
				writer.RenderBeginTag(HtmlTextWriterTag.Input);
				writer.RenderEndTag();
			}
		}
		#endregion
		#endregion
		#endregion
	}
}
